package com.dailyblue.project.smbms.alibaba.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.project.smbms.alibaba.commons.bean.User;
import com.dailyblue.project.smbms.alibaba.commons.util.JsonResult;
import com.dailyblue.project.smbms.alibaba.commons.util.JwtConfig;
import com.dailyblue.project.smbms.alibaba.commons.util.ResultTool;
import com.dailyblue.project.smbms.alibaba.login.handler.PasswordErrorHandler;
import com.dailyblue.project.smbms.alibaba.login.handler.UserNameNotFoundHandler;
import com.dailyblue.project.smbms.alibaba.login.mapper.LoginMapper;
import com.dailyblue.project.smbms.alibaba.login.service.LoginService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, User> implements LoginService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String TOKEN_SUFFIX = "TOKEN:";

    @Override
    public JsonResult login(String name, String pass) {
        // 判断账号是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("userCode", name);
        User user = getOne(wrapper);
        if (user == null) {
            throw new UserNameNotFoundHandler();
        }
        // 判断密码是否一致
        if (!user.getUserPassword().equals(DigestUtils.md5Hex(pass))) {
            throw new PasswordErrorHandler();
        }
        // 生成token
        String token = JwtConfig.getJwtToken(user);
        // 存放到redis中
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        valueOperations.set(TOKEN_SUFFIX + user.getId(), token, 1, TimeUnit.DAYS);
        // 将生成的token返回给前端
        return ResultTool.success(token, user.getUserName());
    }
}
